import fetch from "@/utils/fetch";
import { message } from "antd";

const fetchInstance = fetch.create({
  baseURL: "", // 接口地址
  method: "POST",
  // rest: true,
  header: {
    "Content-Type": "application/json;charset=utf-8",
    env: "dev",
  },
  // 目前还没有做鉴权，下面的设置为`false`，和服务端的*相对应
  // 如果设为`true`，需要服务端设置响应头`Access-Control-Allow-Origin`为具体的白名单
  withCredentials: false,
  responseType: "json",
  transformResponse: [
    function (response) {
      let { code, success, message: msg } = response || {};
      if (response) {
        if (!success && code != 200) {
          if (code === "401") {
            // 退出登录
            sessionStorage.clear();
            window.location.href =
              window.location.origin + window.location.pathname;
          }

          console.log();
          message.error(msg);
          throw new Error(msg);
        }
        return response;
      }
      return {
        success: false,
        data: {},
        message: "网络异常，请刷新页面重试",
        code: "",
      };
    },
  ],
});
const request = fetchInstance.request;
fetchInstance.request = function (opts) {
  if (opts.method === "POST") {
    return request(opts);
  }
  return request(opts);
};
// 统一的返回处理
fetchInstance.interceptors.response.use(
  function (response) {
    return response.data;
  },
  function (error) {
    // alert( JSON.stringify(error) );
    return Promise.reject(error);
  }
);

export default fetchInstance;
